using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using ITProf.Applications.pdb2gac.Attributes;
using ITProf.Applications.pdb2gac.GacUtil;
using ITProf.Applications.pdb2gac.Properties;

namespace ITProf.Applications.pdb2gac
{
// ReSharper disable ClassNeverInstantiated.Global
    internal class Program
// ReSharper restore ClassNeverInstantiated.Global
    {
        private static void Main(string[] args)
        {
            if (args == null || args.Length != 1 || args[0] == null || args[0].Length < 5)
            {
                Console.WriteLine(Resources.InvalidArgumentsText);
                Console.WriteLine(Resources.UsageFormat, Assembly.GetExecutingAssembly().GetName().Name);
                return;
            }
            string pdbFullName = args[0];
            string assemblyName = Path.GetFileNameWithoutExtension(pdbFullName);
            AssemblyInfo? info = GacUtilHelper.GetGacAssemblyInfo(assemblyName);
            if (info == null)
            {
                Console.WriteLine(Resources.GacAssemblyNotRegisteredFormat, assemblyName);
                return;
            }
            string gacPath = BuildGacPath(assemblyName, info);
            if (!Directory.Exists(gacPath))
            {
                Console.WriteLine(Resources.PathNotFoundFormat, gacPath);
                return;
            }
            File.Copy(pdbFullName, Path.Combine(gacPath, Path.GetFileName(pdbFullName)), true);
            Console.WriteLine(Resources.CopiedText);
        }

        private static string BuildGacPath(string assemblyName, AssemblyInfo? info)
        {
            try
            {
                return string.Format(Resources.GacAssemblyFullNameFormat,
                                     Environment.GetEnvironmentVariable("windir"),
                                     AttributeHelper.GetAttributeValue<GacPANameAttribute>(
                                         info.Value.ProcessorArchitecture).Name,
                                     assemblyName,
                                     info.Value.Version,
                                     info.Value.Culture,
                                     info.Value.PublicKeyToken);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
            }
            return string.Empty;
        }
    }
}